<template>
  <el-main class="material-main">
    <div class="main-container">
      <el-row :gutter="20">
        <!-- 右侧内容区 -->
        <el-col :span="24">
          <!-- 查询表单区域 -->
          <el-card class="search-card" shadow="hover">
            <el-form :inline="true" :model="queryParams" ref="queryForm" class="search-form">
              <el-form-item label="物料编码">
                <el-input 
                  v-model="queryParams.materialCode" 
                  placeholder="请输入物料编码" 
                  clearable 
                  prefix-icon="Document"
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
              <el-form-item label="物料名称">
                <el-input 
                  v-model="queryParams.materialName" 
                  placeholder="请输入物料名称" 
                  clearable 
                  prefix-icon="Goods"
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
              <el-form-item label="材质">
                <el-input 
                  v-model="queryParams.materialType" 
                  placeholder="请输入材质" 
                  clearable 
                  prefix-icon="Setting"
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
              <el-form-item class="search-buttons">
                <el-button type="primary" @click="handleQuery" class="search-btn" :icon="Search">
                  查询
                </el-button>
                <el-button @click="resetQuery" class="reset-btn" :icon="Refresh">
                  重置
                </el-button>
                <el-button type="success" @click="handleAdd" class="add-btn" :icon="Plus">
                  新增
                </el-button>
              </el-form-item>
            </el-form>
          </el-card>

          <!-- 表格区域 -->
          <el-card class="table-card" shadow="hover">
            <el-table
              v-loading="loading"
              :data="materialList"
              border
              :height="tableHeight"
              class="data-table"
              highlight-current-row
            >
              <el-table-column type="index" label="序号" width="70" align="center"/>
              <el-table-column prop="materialCode" label="物料编码" min-width="120" align="center" show-overflow-tooltip />
              <el-table-column prop="materialName" label="物料名称" min-width="150" align="center" show-overflow-tooltip />
              <el-table-column prop="unit" label="物料单位" min-width="90" align="center" show-overflow-tooltip />
              <el-table-column prop="specification" label="物料规格" min-width="120" align="center" show-overflow-tooltip />
              <el-table-column prop="materialType" label="材质" min-width="100" align="center" show-overflow-tooltip />
              <el-table-column prop="length" label="长度" min-width="100" align="center" show-overflow-tooltip>
                <template #default="scope">
                  <span v-if="scope.row.length">{{ scope.row.length }}</span>
                  <span v-else class="no-data">-</span>
                </template>
              </el-table-column>
              <el-table-column prop="price" label="含税单价" min-width="130" align="center" show-overflow-tooltip>
                <template #default="scope">
                  <span v-if="scope.row.price">{{ scope.row.price }} 元</span>
                  <span v-else class="no-data">-</span>
                </template>
              </el-table-column>
              <el-table-column prop="purchasePrice" label="采购单价" min-width="130" align="center" show-overflow-tooltip>
                <template #default="scope">
                  <span v-if="scope.row.purchasePrice">{{ scope.row.purchasePrice }} 元</span>
                  <span v-else class="no-data">-</span>
                </template>
              </el-table-column>
              <el-table-column prop="purchaseRatio" label="采购系数" min-width="100" align="center" show-overflow-tooltip />
              <el-table-column prop="power" label="功率" min-width="100" align="center" show-overflow-tooltip />
              <el-table-column prop="electricCurrent" label="电流" min-width="100" align="center" show-overflow-tooltip />
              <el-table-column prop="loadNumber" label="载重" min-width="100" align="center" show-overflow-tooltip />
              <el-table-column prop="arrangeOne" label="列1" min-width="100" align="center" show-overflow-tooltip />
              <el-table-column prop="arrangeTwo" label="列2" min-width="100" align="center" show-overflow-tooltip />
              <el-table-column prop="width" label="货宽" min-width="100" align="center" show-overflow-tooltip />
              <el-table-column prop="category" label="物料类别" min-width="100" align="center" show-overflow-tooltip />
              <el-table-column prop="remark" label="备注" min-width="150" align="center" show-overflow-tooltip />
              <el-table-column label="操作" width="160" fixed="right" align="center">
                <template #default="scope">
                  <div class="action-buttons">
                    <el-button type="primary" size="small" :icon="Edit" @click="handleUpdate(scope.row)" class="edit-btn">
                      编辑
                    </el-button>
                    <el-button type="danger" size="small" :icon="Delete" @click="handleDelete(scope.row)" class="delete-btn">
                      删除
                    </el-button>
                  </div>
                </template>
              </el-table-column>
            </el-table>

            <!-- 分页 -->
            <el-pagination
              v-model:current-page="queryParams.current"
              v-model:page-size="queryParams.size"
              :page-sizes="[10, 20, 50, 100]"
              :total="total"
              layout="total, sizes, prev, pager, next, jumper"
              class="pagination"
              @size-change="getList"
              @current-change="getList"
            />
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 添加或修改设备物料对话框 -->
    <el-dialog 
      :title="title" 
      v-model="open" 
      width="700px" 
      append-to-body
      class="material-dialog"
    >
      <el-scrollbar height="100%" class="form-scrollbar">
        <el-form ref="formRef" :model="form" :rules="rules" label-width="100px" class="material-form">
          <el-card class="form-card" shadow="never">
            <template #header>
              <div class="form-header">
                <el-icon><Document /></el-icon>
                <span>基本信息</span>
              </div>
            </template>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="物料编码" prop="materialCode">
                  <el-input v-model="form.materialCode" placeholder="请输入物料编码" clearable />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="物料名称" prop="materialName">
                  <el-input v-model="form.materialName" placeholder="请输入物料名称" clearable />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="物料单位" prop="unit">
                  <el-input v-model="form.unit" placeholder="请输入物料单位，如：个、千克、米" clearable />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="物料规格" prop="specification">
                  <el-input v-model="form.specification" placeholder="请输入物料规格" clearable />
                </el-form-item>
              </el-col>
            </el-row>
          </el-card>

          <el-card class="form-card" shadow="never">
            <template #header>
              <div class="form-header">
                <el-icon><Setting /></el-icon>
                <span>物料规格参数</span>
              </div>
            </template>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="材质" prop="materialType">
                  <el-input v-model="form.materialType" placeholder="请输入材质" clearable />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="长度" prop="length">
                  <el-input-number 
                    v-model="form.length" 
                    placeholder="请输入长度" 
                    :precision="2"
                    :step="0.1"
                    :min="0"
                    class="full-width"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="含税单价" prop="price">
                  <el-input-number 
                    v-model="form.price" 
                    placeholder="请输入含税单价" 
                    :precision="2"
                    :step="0.1"
                    :min="0"
                    class="full-width"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="采购单价" prop="purchasePrice">
                  <el-input-number 
                    v-model="form.purchasePrice" 
                    placeholder="请输入采购单价" 
                    :precision="2"
                    :step="0.1"
                    :min="0"
                    class="full-width"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="采购系数" prop="purchaseRatio">
                  <el-input-number 
                    v-model="form.purchaseRatio" 
                    placeholder="请输入采购系数" 
                    :precision="2"
                    :step="0.1"
                    :min="0"
                    class="full-width"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="功率" prop="power">
                  <el-input-number 
                    v-model="form.power" 
                    placeholder="请输入功率" 
                    :precision="2"
                    :step="0.1"
                    :min="0"
                    class="full-width"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="电流" prop="electricCurrent">
                  <el-input-number 
                    v-model="form.electricCurrent" 
                    placeholder="请输入电流" 
                    :precision="2"
                    :step="0.1"
                    :min="0"
                    class="full-width"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="载重" prop="loadNumber">
                  <el-input-number 
                    v-model="form.loadNumber" 
                    placeholder="请输入载重" 
                    :precision="2"
                    :step="0.1"
                    :min="0"
                    class="full-width"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="列1" prop="arrangeOne">
                  <el-input-number 
                    v-model="form.arrangeOne" 
                    placeholder="请输入列1" 
                    :precision="2"
                    :step="0.1"
                    :min="0"
                    class="full-width"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="列2" prop="arrangeTwo">
                  <el-input-number 
                    v-model="form.arrangeTwo" 
                    placeholder="请输入列2" 
                    :precision="2"
                    :step="0.1"
                    :min="0"
                    class="full-width"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="货宽" prop="width">
                  <el-input-number 
                    v-model="form.width" 
                    placeholder="请输入货宽" 
                    :precision="2"
                    :step="0.1"
                    :min="0"
                    class="full-width"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="物料类别" prop="category">
                  <el-select 
                    v-model="form.category" 
                    placeholder="请选择物料类别" 
                    clearable 
                    filterable
                    style="width: 220px"
                  >
                  <el-option 
                      v-for="item in typeList" 
                      :key="item.dictLabel" 
                      :label="item.dictLabel" 
                      :value="item.dictLabel" 
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-card>

          <el-card class="form-card" shadow="never">
            <template #header>
              <div class="form-header">
                <el-icon><InfoFilled /></el-icon>
                <span>其他信息</span>
              </div>
            </template>
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="备注" prop="remark">
                  <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-card>
        </el-form>
      </el-scrollbar>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </el-main>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, onUnmounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus'
import { getDeviceMaterialList, getDeviceMaterialDetail, addDeviceMaterial, updateDeviceMaterial, deleteDeviceMaterial } from '@/api/deviceMaterial/index'
import type { DeviceMaterial, DeviceMaterialQuery } from '@/api/deviceMaterial/type'
import { Search, Refresh, Plus, Edit, Delete, Folder, Setting, InfoFilled, Document } from '@element-plus/icons-vue'
import { getListApi as getDictListApi } from "@/api/sysDictData"; // 导入获取项目列表的API
import { SysDictData, SysDictDataListParam } from "@/api/sysDictData/type"; // 导入获取项目列表的API

// 遮罩层
const loading = ref(true)
// 总条数
const total = ref(0)
// 物料表格数据
const materialList = ref([])
// 弹出层标题
const title = ref('')
// 是否显示弹出层
const open = ref(false)
// 表格高度自适应
const tableHeight = ref(0)

// 物料类别列表
const typeList = ref<SysDictData[]>([])
// 获取类型列表
const getTypeList = async () => {
  try {
    const res = await getDictListApi({
        dictType: 'deviceCategory',
        dictName: "",
        status: undefined,
        page: 0,
        limit: 100
    })
    if (res && res.data) {
      typeList.value = res.data.list || []
    }
  } catch (error) {
    console.error('获取类型列表失败:', error)
  }
}

// 查询参数
const queryParams = reactive<DeviceMaterialQuery>({
  current: 1,
  size: 10,
  materialCode: '',
  materialName: '',
  materialType: ''
})

// 表单参数
const form = reactive<DeviceMaterial>({
  id: undefined,
  materialCode: '',
  materialName: '',
  unit: '',
  specification: '',
  materialType: '',
  length: undefined,
  price: undefined,
  purchasePrice: undefined,
  purchaseRatio: undefined,
  power: undefined,
  electricCurrent: undefined,
  loadNumber: undefined,
  arrangeOne: undefined,
  arrangeTwo: undefined,
  width: undefined,
  remark: '',
  category: ''
})

// 表单校验
const rules = {
  materialCode: [
    { required: true, message: '物料编码不能为空', trigger: 'blur' }
  ],
  materialName: [
    { required: true, message: '物料名称不能为空', trigger: 'blur' }
  ]
}

const queryForm = ref<FormInstance>()
const formRef = ref<FormInstance>()

onMounted(() => {
  getTypeList()
  getList()
  // 设置表格高度
  nextTick(() => {
    tableHeight.value = window.innerHeight - 260
  })
})

// 监听窗口大小变化
const handleResize = () => {
  nextTick(() => {
    tableHeight.value = window.innerHeight - 260
  })
}

onMounted(() => {
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
})

// 查询设备物料列表
const getList = () => {
  loading.value = true
  getDeviceMaterialList(queryParams).then((res: any) => {
    materialList.value = res.data.records
    total.value = res.data.total
    loading.value = false
  }).catch(() => {
    loading.value = false
  })
}

// 搜索按钮操作
const handleQuery = () => {
  queryParams.current = 1
  getList()
}

// 重置按钮操作
const resetQuery = () => {
  queryForm.value?.resetFields()
  handleQuery()
}

// 表单重置
const reset = () => {
  form.id = undefined
  form.materialCode = ''
  form.materialName = ''
  form.unit = ''
  form.specification = ''
  form.materialType = ''
  form.length = undefined
  form.price = undefined
  form.purchasePrice = undefined
  form.purchaseRatio = undefined
  form.power = undefined
  form.electricCurrent = undefined
  form.loadNumber = undefined
  form.arrangeOne = undefined
  form.arrangeTwo = undefined
  form.width = undefined
  form.remark = ''
  form.category = ''
  formRef.value?.resetFields()
}

// 新增按钮操作
const handleAdd = () => {
  reset()
  open.value = true
  title.value = '添加设备物料'
}

// 修改按钮操作
const handleUpdate = (row: any) => {
  reset()
  const id = row.id
  getDeviceMaterialDetail(id).then((res: any) => {
    Object.assign(form, res.data)
    open.value = true
    title.value = '修改设备物料'
  })
}

// 提交按钮
const submitForm = () => {
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      if (form.id) {
        updateDeviceMaterial(form).then(() => {
          ElMessage.success('修改成功')
          open.value = false
          getList()
        })
      } else {
        addDeviceMaterial(form).then(() => {
          ElMessage.success('新增成功')
          open.value = false
          getList()
        })
      }
    }
  })
}

// 删除按钮操作
const handleDelete = (row: any) => {
  const id = row.id
  ElMessageBox.confirm('是否确认删除该设备物料？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteDeviceMaterial(id).then(() => {
      getList()
      ElMessage.success('删除成功')
    })
  })
}

// 取消按钮
const cancel = () => {
  open.value = false
  reset()
}
</script>

<style scoped lang="scss">
.material-main {
  padding: 0;
}

.main-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.search-card {
  margin-bottom: 20px;
  border-radius: 8px;
  transition: all 0.3s;
  
  :deep(.el-card__body) {
    padding: 15px 20px;
  }
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  
  .el-form-item {
    margin-bottom: 0;
    margin-right: 16px;
  }
  
  .search-buttons {
    margin-left: auto;
    
    .el-button {
      margin-left: 8px;
      transition: all 0.3s;
      
      &:first-child {
        margin-left: 0;
      }
    }
    
    .search-btn {
      background: linear-gradient(135deg, #1989fa, #0056b3);
      border: none;
      
      &:hover {
        opacity: 0.9;
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(25, 137, 250, 0.3);
      }
    }
    
    .add-btn {
      background: linear-gradient(135deg, #67c23a, #409eff);
      border: none;
      
      &:hover {
        opacity: 0.9;
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(103, 194, 58, 0.3);
      }
    }
    
    .reset-btn:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(144, 147, 153, 0.2);
    }
  }
}

.table-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  height: calc(100vh - 180px);
  margin-bottom: 0;
  
  :deep(.el-card__body) {
    padding: 0;
    height: 100%;
    display: flex;
    flex-direction: column;
  }
}

.data-table {
  border-radius: 4px;
  flex: 1;
  
  :deep(.el-table__header-wrapper) {
    th {
      background-color: #f2f6fc;
      font-weight: 600;
    }
  }
  
  :deep(.el-table__row) {
    &:hover {
      td {
        background-color: #ecf5ff;
      }
    }
  }
  
  .no-data {
    color: #c0c4cc;
  }
  
  .action-buttons {
    display: flex;
    justify-content: center;
    
    .el-button {
      padding: 6px 10px;
      transition: all 0.3s;
      
      &:hover {
        transform: translateY(-2px);
      }
    }
    
    .edit-btn {
      margin-right: 10px;
    }
  }
}

.pagination {
  padding: 15px 20px;
  justify-content: flex-end;
  background: #fff;
  border-radius: 0 0 8px 8px;
}

// 弹窗样式
:deep(.material-dialog) {
  border-radius: 8px;
  overflow: hidden;
  
  .el-dialog__header {
    padding: 15px 20px;
    margin: 0;
    background: linear-gradient(90deg, #f0f9eb, #e1f3d8);
    border-bottom: 1px solid #e1f3d8;
    
    .el-dialog__title {
      font-size: 16px;
      font-weight: 600;
      color: #67c23a;
    }
    
    .el-dialog__headerbtn {
      top: 15px;
    }
  }
  
  .el-dialog__body {
    padding: 0;
  }
  
  .el-dialog__footer {
    padding: 10px 20px;
    border-top: 1px solid #ebeef5;
    background-color: #f5f7fa;
    
    .el-button {
      padding: 8px 20px;
      border-radius: 4px;
      transition: all 0.3s;
      
      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
      }
    }
  }
}

.form-scrollbar {
  max-height: calc(80vh - 120px);
  overflow-y: auto;
}

.material-form {
  padding: 20px;
  
  .form-card {
    margin-bottom: 15px;
    border-radius: 8px;
    transition: all 0.3s;
    overflow: hidden;
    border: 1px solid #ebeef5;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    :deep(.el-card__header) {
      padding: 10px 15px;
      background: linear-gradient(90deg, #f0f9eb, #e1f3d8);
      border-bottom: 1px solid #e1f3d8;
    }
    
    .form-header {
      font-size: 16px;
      font-weight: 600;
      color: #67c23a;
      display: flex;
      align-items: center;
      gap: 8px;
      
      .el-icon {
        color: #67c23a;
      }
    }
  }

  :deep(.el-input), :deep(.el-select), :deep(.el-input-number) {
    width: 100%;
  }
  
  :deep(.el-input__wrapper), :deep(.el-textarea__inner) {
    box-shadow: 0 0 0 1px #dcdfe6 inset;
    
    &:hover {
      box-shadow: 0 0 0 1px #c0c4cc inset;
    }
    
    &.is-focus {
      box-shadow: 0 0 0 1px #67c23a inset;
    }
  }
  
  :deep(.el-form-item__label) {
    font-weight: 500;
  }
}

.full-width {
  width: 100%;
}
</style> 